package com.redriver.hospitalsystem.systemgetway.handler;

import com.RedRiver.hospitalsystem.result.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.redriver.hospitalsystem.systemgetway.exception.ExceptionHandler;
import com.redriver.hospitalsystem.systemgetway.exception.GatewayException;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@Component
public class GloabExceptionHandler implements ErrorWebExceptionHandler {

    ObjectMapper objectMapper = new ObjectMapper();
    @Resource
    GatewayException ge;

    @Override
    public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable throwable) {
        Method[] declaredMethods = ge.getClass().getDeclaredMethods();
        Result<?> result = Result.getInstance().setCode(50000).setMsg("token不存在或token已过期，请重新登录");
        for (Method method : declaredMethods) {
            ExceptionHandler declaredAnnotation = method.getDeclaredAnnotation(ExceptionHandler.class);
            if (ObjectUtils.isEmpty(declaredAnnotation)) {
                continue;
            }
            Class value = declaredAnnotation.value();
            if (value.getTypeName().equals(throwable.getClass().getTypeName())) {
                try {
                    result = (Result<?>) method.invoke(ge, throwable);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }

            }
        }
        serverWebExchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
        try {
            final String json = objectMapper.writeValueAsString(result);

            //做响应
            return serverWebExchange.getResponse().writeWith(Mono.fromSupplier(() -> {
                return serverWebExchange.getResponse().bufferFactory().wrap(json.getBytes());
            }));

        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
